import time
import dashscope
import os
import datetime
import json
from dashscope import Generation

dashscope.api_key = "sk-da1d85ca047141b2b609854ead685cb8"
file_content = ""
grade = ""
file_id = ""
file_title = ""
jg = ""
nr = ""
sx = ""
yyb = ""
ztly = ""
zp = ""

jg_format = ""
nr_format = ""
sx_format = ""
yybd_format = ""
ztly_format = ""
zp_format = ""

messageJG = [{'role': 'system', 'content': '你是一个小学语文老师(请你模拟真实教师的语气,注意-不要出现"作者"称呼)'},
             {'role': 'user', 'content': ''}]
messageNR = [{'role': 'system', 'content': '你是一个小学语文老师(请你模拟真实教师的语气,注意-不要出现"作者"称呼)'},
             {'role': 'user', 'content': ''}]
messageSX = [{'role': 'system', 'content': '你是一个小学语文老师(请你模拟真实教师的语气,注意-不要出现"作者"称呼)'},
             {'role': 'user', 'content': ''}]
messageYYBD = [{'role': 'system', 'content': '你是一个小学语文老师(请你模拟真实教师的语气,注意-不要出现"作者"称呼)'},
               {'role': 'user', 'content': ''}]
messageZTLY = [{'role': 'system', 'content': '你是一个小学语文老师(请你模拟真实教师的语气,注意-不要出现"作者"称呼)'},
               {'role': 'user', 'content': ''}]
messageZP = [{'role': 'system', 'content': '你是一个小学语文老师(请你模拟真实教师的语气,注意-不要出现"作者"称呼)'},
             {'role': 'user', 'content': ''}]

dims = [
    "结构",
    "内容",
    "书写",
    "语言表达",
    "主题立意",
    "总评"
]

read_folder_path = "../zuowen"
write_folder_path = '../Tongyiqianwen'
format_folder_path = "../OutputFormat"


def update_msg(temp):
    global messageJG,messageZP,messageNR,messageSX,messageYYBD,messageZTLY
    if temp == "结构":
        messageJG[1]['content'] = jg_format.replace("{file_content}", file_content)
        messageJG[1]['content'] = messageJG[1]['content'].replace("{grade}", grade)
        messageJG[1]['content'] = messageJG[1]['content'].replace("{file_id}", file_id)
        messageJG[1]['content'] = messageJG[1]['content'].replace("{file_title}", file_title)
    elif temp == "内容":
        messageNR[1]['content'] = nr_format.replace("{file_content}", file_content)
        messageNR[1]['content'] = messageNR[1]['content'].replace("{grade}", grade)
        messageNR[1]['content'] = messageNR[1]['content'].replace("{file_id}", file_id)
        messageNR[1]['content'] = messageNR[1]['content'].replace("{file_title}", file_title)
    elif temp == "书写":
        messageSX[1]['content'] = sx_format.replace("{file_content}", file_content)
        messageSX[1]['content'] = messageSX[1]['content'].replace("{grade}", grade)
        messageSX[1]['content'] = messageSX[1]['content'].replace("{file_id}", file_id)
        messageSX[1]['content'] = messageSX[1]['content'].replace("{file_title}", file_title)
    elif temp == "语言表达":
        messageYYBD[1]['content'] = yybd_format.replace("{file_content}", file_content)
        messageYYBD[1]['content'] = messageYYBD[1]['content'].replace("{grade}", grade)
        messageYYBD[1]['content'] = messageYYBD[1]['content'].replace("{file_id}", file_id)
        messageYYBD[1]['content'] = messageYYBD[1]['content'].replace("{file_title}", file_title)
    elif temp == "主题立意":
        messageZTLY[1]['content'] = ztly_format.replace("{file_content}", file_content)
        messageZTLY[1]['content'] = messageZTLY[1]['content'].replace("{grade}", grade)
        messageZTLY[1]['content'] = messageZTLY[1]['content'].replace("{file_id}", file_id)
        messageZTLY[1]['content'] = messageZTLY[1]['content'].replace("{file_title}", file_title)
    elif temp == "总评":
        messageZP[1]['content'] = zp_format.replace("{file_content}", file_content)
        messageZP[1]['content'] = messageZP[1]['content'].replace("{grade}", grade)
        messageZP[1]['content'] = messageZP[1]['content'].replace("{file_id}", file_id)
        messageZP[1]['content'] = messageZP[1]['content'].replace("{file_title}", file_title)
        messageZP[1]['content'] = messageZP[1]['content'].replace("{jg}", jg)
        messageZP[1]['content'] = messageZP[1]['content'].replace("{nr}", nr)
        messageZP[1]['content'] = messageZP[1]['content'].replace("{sx}", sx)
        messageZP[1]['content'] = messageZP[1]['content'].replace("{yyb.txt}", yyb)
        messageZP[1]['content'] = messageZP[1]['content'].replace("{ztly}", ztly)

for root, dirs, files in os.walk(format_folder_path):
    for file in files:
        file_path = os.path.join(root, file)
        with open(file_path, 'r', encoding='utf-8') as f:
            file_format = f.read()
            base_name = file.rsplit('.', 1)[0]
            if base_name == "jg":
                jg_format = file_format
            elif base_name == "nr":
                nr_format = file_format
            elif base_name == "sx":
                sx_format = file_format
            elif base_name == "yyb":
                yybd_format = file_format
            elif base_name == "ztly":
                ztly_format = file_format
            elif base_name == "zp":
                zp_format = file_format

def call_api(messages, grade, file_id, file_title, write_folder_path, temp_category):
    global jg, nr, sx, yyb, ztly, zp, data
    write_file_path = os.path.join(write_folder_path, f'{grade}-{file_id}-{file_title}-{temp_category}.txt')
    start_time = time.time()
    response = Generation.call(
        api_key="sk-da1d85ca047141b2b609854ead685cb8",
        model="qwen-plus",
        messages=messages,
        result_format="message"
    )

    if response.status_code == 200:
        end_time = time.time()
        if temp_category == "结构":
            jg = response.output.choices[0].message.content
            data = json.loads(jg)
        elif temp_category == "内容":
            nr = response.output.choices[0].message.content
            data = json.loads(nr)
        elif temp_category == "书写":
            sx = response.output.choices[0].message.content
            data = json.loads(sx)
        elif temp_category == "语言表达":
            yyb = response.output.choices[0].message.content
            #data = json.loads(yyb)
        elif temp_category == "主题立意":
            ztly = response.output.choices[0].message.content
            data = json.loads(ztly)
        #print(data, type(data))
        with open(write_file_path, 'a', encoding='utf-8') as write_file:
            response_time = end_time - start_time
            response_time_str = f"{response_time:.6f}"
            write_file.write(f"请求时间戳：{datetime.datetime.now()}秒\n")
            write_file.write(f"response time：总耗时：{response_time_str}秒\n")
            if temp_category == "结构":
                write_file.write(f"response content：{jg}\n")
            elif temp_category == "内容":
                write_file.write(f"response content：{nr}\n")
            elif temp_category == "书写":
                write_file.write(f"response content：{sx}\n")
            elif temp_category == "语言表达":
                write_file.write(f"response content：{yyb}\n")
            elif temp_category == "主题立意":
                write_file.write(f"response content：{ztly}\n")
            elif temp_category == "总评":
                write_file.write(f"response content：{zp}\n")
            write_file.write("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")
    else:
        print(f"错误码：{response.code}")


for root, dirs, files in os.walk(read_folder_path):
    for file in files:
        file_path = os.path.join(root, file)
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            file_content = ''.join(lines[1:])
            base_name = file.rsplit('.', 1)[0]
            parts = base_name.split('-')
            grade = parts[0]
            file_id = parts[1]
            file_title = parts[2]
            for dim in dims:
                print(f"正在批改{file_title}的{dim}...")
                update_msg(dim)
                if dim == "结构":
                    continue
                    call_api(messageJG, grade, file_id, file_title, write_folder_path, dim)
                elif dim == "内容":
                    continue
                    call_api(messageNR, grade, file_id, file_title, write_folder_path, dim)
                elif dim == "书写":
                    continue
                    call_api(messageSX, grade, file_id, file_title, write_folder_path, dim)
                elif dim == "语言表达":
                    call_api(messageYYBD, grade, file_id, file_title, write_folder_path, dim)
                elif dim == "主题立意":
                    continue
                    call_api(messageZTLY, grade, file_id, file_title, write_folder_path, dim)
                elif dim == "总评":
                    continue
                    call_api(messageZP, grade, file_id, file_title, write_folder_path, dim)

